package com.wbao.dianniu.utils;

import android.Manifest;
import android.app.Activity;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.hardware.Camera;
import android.net.Uri;
import android.os.Build;
import android.os.Environment;
import android.os.StrictMode;
import android.provider.MediaStore;
import android.provider.Settings;
import android.support.v4.app.FragmentActivity;
import android.support.v4.content.ContextCompat;
import android.support.v4.content.FileProvider;
import android.text.TextUtils;

import com.mylhyl.acp.Acp;
import com.mylhyl.acp.AcpListener;
import com.mylhyl.acp.AcpOptions;
import com.permissionutil.PermissionListener;
import com.permissionutil.PermissionUtil;
import com.wbao.dianniu.customView.CustomDialog;
import com.wbao.dianniu.ui.InviteFriendActivity;
import com.wbao.dianniu.ui.WeChatCaptureActivity;

import java.io.File;
import java.util.List;

/**
 * 权限处理类
 * <p>
 * Created by yejianjun on 2017/11/18.
 */

public class PermissionUtils {

    public static final int TAKE_PHOTO = 2; // 打开图片标记

    private static PermissionUtils instance;

    public static PermissionUtils getInstance() {
        if (null == instance) {
            instance = new PermissionUtils();
        }
        return instance;
    }

    public boolean intentToCall(final Context context, final String phoneNumber) {
        if (context == null || TextUtils.isEmpty(phoneNumber)) {
            return false;
        }
        //6.0权限处理
        Acp.getInstance(context).request(new AcpOptions.Builder().setPermissions(
                Manifest.permission.CALL_PHONE).build(), new AcpListener() {
            @Override
            public void onGranted() {
                if (ContextCompat.checkSelfPermission(context, Manifest.permission.CALL_PHONE) == PackageManager.PERMISSION_GRANTED) {
                    Uri u = Uri.parse("tel:" + phoneNumber);
                    Intent it = new Intent(Intent.ACTION_CALL, u);
                    context.startActivity(it);
                }
            }

            @Override
            public void onDenied(List<String> permissions) {
                Notification.toast(context, permissions.toString() + "权限拒绝");
            }
        });

        return true;
    }


    public boolean intentToCamera(final Activity activity) {
        if (activity == null) {
            return false;
        }
        //6.0权限处理
        Acp.getInstance(activity).request(new AcpOptions.Builder().setPermissions(
                Manifest.permission.CAMERA).build(), new AcpListener() {
            @Override
            public void onGranted() {
                try {
                    if (Build.VERSION.SDK_INT >= 24) {
                        //拍照  解决7.0系统权限问题
                        File newFile = new File(Environment.getExternalStorageDirectory(), "temp.jpg");
                        Uri tempUri = FileProvider.getUriForFile(activity, "com.wbao.dianniu.fileprovider", newFile);
                        Intent takeIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
                        takeIntent.putExtra(MediaStore.EXTRA_OUTPUT, tempUri); // 授予目录临时共享权限
                        takeIntent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION | Intent.FLAG_GRANT_WRITE_URI_PERMISSION);
                        activity.startActivityForResult(takeIntent, TAKE_PHOTO);
                    } else {
                        //拍照
                        Intent takeIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
                        takeIntent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(new File(Environment.getExternalStorageDirectory(), "temp.jpg")));
                        activity.startActivityForResult(takeIntent, TAKE_PHOTO);
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }

            }

            @Override
            public void onDenied(List<String> permissions) {
                Notification.toast(activity, permissions.toString() + "权限拒绝");
            }
        });

        return true;
    }

    /**
     * @param activity
     * @param requestCode
     * @param type        1: 基本图片intent 2：image目录下 3：传入uri参数
     * @return
     */
    public boolean intentToPhoto(final Activity activity, final int requestCode, final int type, final Uri mImageUri) {
        if (null == activity) {
            return false;
        }

        //6.0权限处理
        Acp.getInstance(activity).request(new AcpOptions.Builder().setPermissions(
                Manifest.permission.READ_EXTERNAL_STORAGE).build(), new AcpListener() {
            @Override
            public void onGranted() {
                try {
                    Intent intent = new Intent(Intent.ACTION_PICK);
                    if (2 == type) {
                        intent.setType("image/*");
                    } else if (3 == type && null != mImageUri) {
                        intent.setDataAndType(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, "image/*");
                        intent.putExtra(MediaStore.EXTRA_OUTPUT, mImageUri);
                    } else {
                        intent.setData(MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
                    }
                    activity.startActivityForResult(intent, requestCode);
                } catch (Exception e) {
                    e.printStackTrace();
                }

            }

            @Override
            public void onDenied(List<String> permissions) {
                Notification.toast(activity, permissions.toString() + "权限拒绝");
            }
        });

        return true;
    }


    public Uri openUri(File file) {
        Uri uri = null;
        try {
            if (Build.VERSION.SDK_INT >= 24) {
                StrictMode.VmPolicy.Builder builder = new StrictMode.VmPolicy.Builder();
                StrictMode.setVmPolicy(builder.build());
                uri = Uri.fromFile(file);
            } else {
                uri = Uri.fromFile(file);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return uri;
    }

    /**
     * 扫一扫调用相机权限
     *
     * @param activity
     */
    public boolean intentToScan(final FragmentActivity activity) {
        if (activity == null) {
            return false;
        }

        PermissionUtil permissionUtil = new PermissionUtil(activity);
        permissionUtil.requestPermissions(new String[]{Manifest.permission.CAMERA, Manifest.permission.WRITE_EXTERNAL_STORAGE},
                new PermissionListener() {
                    @Override
                    public void onGranted() {
                        try {
                            // sdk低于23的手机，会直接申请权限，此时需要先检测权限是否获取
                            Camera camera = Camera.open();
                            camera.release();
                            camera = null;
                            //所有权限都已经授权
                            Intent intent = new Intent();
                            intent.setClass(activity, WeChatCaptureActivity.class);
                            activity.startActivity(intent);
                        } catch (Exception e) {
                            PermissionUtils.getInstance().showMsg(activity, "权限被拒绝，此功能不能正常使用，\n请点击\"设置\"-\"权限管理\"-打开所有权限");
                        }
                    }

                    @Override
                    public void onDenied(List<String> list) {
                        //Toast第一个被拒绝的权限
                        //showMsg("您拒绝权限申请，此功能将不能正常使用，您可以去设置页面重新授权");
                        showMsg(activity, "权限被拒绝，此功能不能正常使用。\n请点击\"设置\"-\"权限管理\"-打开所有权限");
                    }

                    @Override
                    public void onShouldShowRationale(List<String> list) {
                        //Toast第一个勾选不在提示的权限
                        showMsg(activity, "权限被拒绝，此功能不能正常使用。\n请点击\"设置\"-\"权限管理\"-打开所有权限");
                    }
                });


        //6.0权限处理
        /*Acp.getInstance(activity).request(new AcpOptions.Builder().setPermissions(
                Manifest.permission.CAMERA, Manifest.permission.WRITE_EXTERNAL_STORAGE).build(), new AcpListener() {
            @Override
            public void onGranted() {
                Intent intent = new Intent();
                intent.setClass(activity, WeChatCaptureActivity.class);
                activity.startActivity(intent);
            }

            @Override
            public void onDenied(List<String> permissions) {
                Notification.toast(activity, permissions.toString() + "权限拒绝");
            }
        });*/

        return true;

    }

    /**
     * 发短信权限
     *
     * @param mContext
     */
    public boolean intentToSendSMS(final Context mContext, final String phone, final String message) {
        if (mContext == null) {
            return false;
        }
        //6.0权限处理
        Acp.getInstance(mContext).request(new AcpOptions.Builder().setPermissions(
                Manifest.permission.SEND_SMS).build(), new AcpListener() {
            @Override
            public void onGranted() {
                Intent intent = new Intent(Intent.ACTION_SENDTO, Uri.parse("smsto:" + phone));
                intent.putExtra("sms_body", message == null ? "" : message);
                mContext.startActivity(intent);
            }

            @Override
            public void onDenied(List<String> permissions) {
                Notification.toast(mContext, permissions.toString() + "权限拒绝");
            }
        });

        return true;
    }

    public boolean intentToContact(final Context mContext) {
        if (mContext == null) {
            return false;
        }
        //6.0权限处理
        Acp.getInstance(mContext).request(new AcpOptions.Builder().setPermissions(
                Manifest.permission.GET_ACCOUNTS, Manifest.permission.READ_CONTACTS).build(), new AcpListener() {
            @Override
            public void onGranted() {
                Intent inviteIntent = new Intent();
                inviteIntent.setClass(mContext, InviteFriendActivity.class);
                mContext.startActivity(inviteIntent);
            }

            @Override
            public void onDenied(List<String> permissions) {
                Notification.toast(mContext, permissions.toString() + "权限拒绝");
            }
        });

        return true;
    }


    public void showMsg(final Activity activity, String msg) {
        CustomDialog.Builder builder = new CustomDialog.Builder(activity);
        builder.setMessage(msg);
        builder.setTitleVisbily(false);
        builder.setPositiveButton("设置权限", new DialogInterface.OnClickListener() {
            public void onClick(DialogInterface dialog, int which) {
                dialog.dismiss();
                goToAppSetting(activity);
            }
        });
        builder.setNegativeButton("关闭",
                new DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface dialog, int which) {
                        dialog.dismiss();
                    }
                });
        builder.create().show();
    }

    /**
     * 打开Setting
     */
    private void goToAppSetting(Activity activity) {
        Intent intent = new Intent();
        intent.setAction(Settings.ACTION_APPLICATION_DETAILS_SETTINGS);
        Uri uri = Uri.fromParts("package", "com.wbao.dianniu", null);
        intent.setData(uri);
        activity.startActivityForResult(intent, 123);
    }

    // 6.0系统读取联系人权限

    public boolean getLocation(final FragmentActivity activity){

        if (activity == null) {
            return false;
        }

        PermissionUtil permissionUtil = new PermissionUtil(activity);
        permissionUtil.requestPermissions(new String[]{Manifest.permission.ACCESS_FINE_LOCATION, Manifest.permission.ACCESS_COARSE_LOCATION,Manifest.permission.ACCESS_WIFI_STATE},
                new PermissionListener() {
                    @Override
                    public void onGranted() {
                        try {

                        } catch (Exception e) {
                            PermissionUtils.getInstance().showMsg(activity, "权限被拒绝，此功能不能正常使用，\n请点击\"设置\"-\"权限管理\"-打开所有权限");
                        }
                    }

                    @Override
                    public void onDenied(List<String> list) {
                        //Toast第一个被拒绝的权限
                        //showMsg("您拒绝权限申请，此功能将不能正常使用，您可以去设置页面重新授权");
                        showMsg(activity, "权限被拒绝，此功能不能正常使用。\n请点击\"设置\"-\"权限管理\"-打开所有权限");
                    }

                    @Override
                    public void onShouldShowRationale(List<String> list) {
                        //Toast第一个勾选不在提示的权限
                        showMsg(activity, "权限被拒绝，此功能不能正常使用。\n请点击\"设置\"-\"权限管理\"-打开所有权限");
                    }
                });

        return true;
    }


}
